#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

Linux发行版检测模块
包含各种Linux发行版的检测和版本信息获取功能
"""

import os
import re
import platform
from .utils import ml, SystemInfo


def get_system_architecture():
    """
    获取系统架构信息，兼容Windows和Linux系统
    
    Returns:
        str: 系统架构信息
    """
    try:
        if os.name == 'nt':  # Windows 系统
            return platform.machine()
        else:  # Linux/Unix 系统
            arch_output = ml('uname -m').strip()
            return arch_output if arch_output else platform.machine()
    except Exception:
        try:
            return platform.machine()
        except Exception:
            return 'unknown'


def detect_linux_distro():
    """
    检测Linux发行版类型
    
    Returns:
        str: 发行版类型标识符
    """
    try:
        # 检查/etc/os-release文件
        if os.path.exists('/etc/os-release'):
            with open('/etc/os-release', 'r') as f:
                os_release = f.read().lower()
                
                # 检测各种发行版
                if 'ubuntu' in os_release:
                    return 'debian_based'
                elif 'debian' in os_release:
                    return 'debian_based'
                elif 'fedora' in os_release:
                    return 'fedora_based'
                elif 'centos stream' in os_release:
                    return 'centos_stream_based'
                elif 'centos' in os_release:
                    return 'centos_based'
                elif 'rhel' in os_release or 'red hat' in os_release:
                    return 'rhel_based'
                elif 'rocky' in os_release:
                    return 'rhel_based'
                elif 'almalinux' in os_release or 'alma linux' in os_release:
                    return 'rhel_based'
                elif 'opensuse' in os_release or 'suse' in os_release:
                    return 'suse_based'
                elif 'alpine' in os_release:
                    return 'alpine_based'
                elif 'alibaba' in os_release or 'alinux' in os_release:
                    return 'alibaba_based'
                elif 'anolis' in os_release:
                    return 'anolis_based'
        
        # 检查其他release文件
        release_files = [
            ('/etc/redhat-release', 'rhel_based'),
            ('/etc/debian_version', 'debian_based'),
            ('/etc/fedora-release', 'fedora_based'),
            ('/etc/centos-release', 'centos_based'),
            ('/etc/SuSE-release', 'suse_based'),
            ('/etc/alpine-release', 'alpine_based')
        ]
        
        for file_path, distro_type in release_files:
            if os.path.exists(file_path):
                return distro_type
        
        # 使用lsb_release命令
        try:
            lsb_output = ml('lsb_release -i 2>/dev/null').lower()
            if 'ubuntu' in lsb_output or 'debian' in lsb_output:
                return 'debian_based'
            elif 'fedora' in lsb_output:
                return 'fedora_based'
            elif 'centos' in lsb_output:
                return 'centos_based'
            elif 'redhat' in lsb_output or 'rhel' in lsb_output:
                return 'rhel_based'
            elif 'suse' in lsb_output:
                return 'suse_based'
        except (OSError, subprocess.CalledProcessError) as e:
            # LSB命令执行失败，继续使用其他方法检测
            pass
        
        return 'unknown'
        
    except Exception as e:
        # 记录异常但不中断程序
        import logging
        logging.warning(f"发行版检测失败: {e}")
        return 'unknown'


def detect_ubuntu_version():
    """
    检测Ubuntu详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    ubuntu_info = {
        'is_ubuntu': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'codename': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'lts', 'current', 'eol', 'none'
    }
    
    try:
        # 检查是否为Ubuntu系统
        is_ubuntu = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            with open('/etc/os-release', 'r') as f:
                os_release = f.read().lower()
                if 'ubuntu' in os_release:
                    is_ubuntu = True
                    ubuntu_info['is_ubuntu'] = True
                    
                    # 提取版本信息
                    for line in os_release.split('\n'):
                        if 'version_id=' in line:
                            version = line.split('=')[1].strip('"\'')
                            ubuntu_info['version'] = version
                            # 解析主版本号和次版本号
                            if '.' in version:
                                parts = version.split('.')
                                ubuntu_info['major_version'] = parts[0]
                                ubuntu_info['minor_version'] = parts[1]
                            else:
                                ubuntu_info['major_version'] = version
                                ubuntu_info['minor_version'] = '0'
                        elif 'version_codename=' in line:
                            codename = line.split('=')[1].strip('"\'')
                            ubuntu_info['codename'] = codename
        
        # 方法2: 检查lsb_release命令
        if not is_ubuntu:
            try:
                lsb_output = ml('lsb_release -a 2>/dev/null')
                if 'ubuntu' in lsb_output.lower():
                    is_ubuntu = True
                    ubuntu_info['is_ubuntu'] = True
                    
                    # 从lsb_release输出中提取版本信息
                    for line in lsb_output.split('\n'):
                        if 'release:' in line.lower():
                            version = line.split(':')[1].strip()
                            ubuntu_info['version'] = version
                            if '.' in version:
                                parts = version.split('.')
                                ubuntu_info['major_version'] = parts[0]
                                ubuntu_info['minor_version'] = parts[1]
                        elif 'codename:' in line.lower():
                            codename = line.split(':')[1].strip()
                            ubuntu_info['codename'] = codename
            except (OSError, IOError) as e:
                # 文件读取失败，使用默认值
                pass
        
        if not is_ubuntu:
            return ubuntu_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                ubuntu_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                ubuntu_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                ubuntu_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                ubuntu_info['architecture'] = 'ARM32'
            else:
                ubuntu_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                ubuntu_info['is_uefi'] = True
            else:
                ubuntu_info['is_uefi'] = False
        except:
            ubuntu_info['is_uefi'] = False
        
        # 定义支持的Ubuntu版本和EOL状态
        ubuntu_versions = {
            # LTS版本
            '24.04': {'codename': 'noble', 'lts': True, 'eol': False, 'support': 'lts'},
            '22.04': {'codename': 'jammy', 'lts': True, 'eol': False, 'support': 'lts'},
            '20.04': {'codename': 'focal', 'lts': True, 'eol': False, 'support': 'lts'},
            '18.04': {'codename': 'bionic', 'lts': True, 'eol': True, 'support': 'eol'},
            '16.04': {'codename': 'xenial', 'lts': True, 'eol': True, 'support': 'eol'},
            '14.04': {'codename': 'trusty', 'lts': True, 'eol': True, 'support': 'eol'},
            
            # 非LTS版本
            '23.10': {'codename': 'mantic', 'lts': False, 'eol': True, 'support': 'eol'},
            '23.04': {'codename': 'lunar', 'lts': False, 'eol': True, 'support': 'eol'},
            '22.10': {'codename': 'kinetic', 'lts': False, 'eol': True, 'support': 'eol'},
            '21.10': {'codename': 'impish', 'lts': False, 'eol': True, 'support': 'eol'},
            '21.04': {'codename': 'hirsute', 'lts': False, 'eol': True, 'support': 'eol'},
            '20.10': {'codename': 'groovy', 'lts': False, 'eol': True, 'support': 'eol'},
            '19.10': {'codename': 'eoan', 'lts': False, 'eol': True, 'support': 'eol'},
            '19.04': {'codename': 'disco', 'lts': False, 'eol': True, 'support': 'eol'},
            '18.10': {'codename': 'cosmic', 'lts': False, 'eol': True, 'support': 'eol'},
            '17.10': {'codename': 'artful', 'lts': False, 'eol': True, 'support': 'eol'},
            '17.04': {'codename': 'zesty', 'lts': False, 'eol': True, 'support': 'eol'},
            '16.10': {'codename': 'yakkety', 'lts': False, 'eol': True, 'support': 'eol'},
            '15.10': {'codename': 'wily', 'lts': False, 'eol': True, 'support': 'eol'},
            '15.04': {'codename': 'vivid', 'lts': False, 'eol': True, 'support': 'eol'},
            '14.10': {'codename': 'utopic', 'lts': False, 'eol': True, 'support': 'eol'},
            '13.10': {'codename': 'saucy', 'lts': False, 'eol': True, 'support': 'eol'},
            '13.04': {'codename': 'raring', 'lts': False, 'eol': True, 'support': 'eol'},
            '12.10': {'codename': 'quantal', 'lts': False, 'eol': True, 'support': 'eol'},
            '12.04': {'codename': 'precise', 'lts': True, 'eol': True, 'support': 'eol'},
            '11.10': {'codename': 'oneiric', 'lts': False, 'eol': True, 'support': 'eol'},
            '11.04': {'codename': 'natty', 'lts': False, 'eol': True, 'support': 'eol'},
            '10.10': {'codename': 'maverick', 'lts': False, 'eol': True, 'support': 'eol'},
            '10.04': {'codename': 'lucid', 'lts': True, 'eol': True, 'support': 'eol'}
        }
        
        # 检查版本支持状态
        if ubuntu_info['version'] in ubuntu_versions:
            version_info = ubuntu_versions[ubuntu_info['version']]
            ubuntu_info['is_eol'] = version_info['eol']
            ubuntu_info['support_level'] = version_info['support']
            ubuntu_info['supported'] = True
            
            # 设置代号（如果未从os-release获取）
            if ubuntu_info['codename'] == 'unknown':
                ubuntu_info['codename'] = version_info['codename']
        
        return ubuntu_info
        
    except Exception as e:
        return ubuntu_info


def detect_centos_stream_version():
    """
    检测CentOS Stream详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    centos_stream_info = {
        'is_centos_stream': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'current', 'supported', 'eol', 'none'
    }
    
    try:
        # 检查是否为CentOS Stream系统
        is_centos_stream = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            with open('/etc/os-release', 'r') as f:
                os_release = f.read().lower()
                if 'centos stream' in os_release or ('centos' in os_release and 'stream' in os_release):
                    is_centos_stream = True
                    centos_stream_info['is_centos_stream'] = True
                    
                    # 提取版本信息
                    for line in os_release.split('\n'):
                        if 'version_id=' in line:
                            version = line.split('=')[1].strip('"\'')
                            centos_stream_info['version'] = version
                            # 解析主版本号和次版本号
                            if '.' in version:
                                parts = version.split('.')
                                centos_stream_info['major_version'] = parts[0]
                                centos_stream_info['minor_version'] = parts[1]
                            else:
                                centos_stream_info['major_version'] = version
                                centos_stream_info['minor_version'] = '0'
        
        # 方法2: 检查/etc/centos-release
        if not is_centos_stream and os.path.exists('/etc/centos-release'):
            try:
                with open('/etc/centos-release', 'r') as f:
                    centos_release = f.read().strip()
                    if 'stream' in centos_release.lower():
                        is_centos_stream = True
                        centos_stream_info['is_centos_stream'] = True
                        
                        # 从release文件中提取版本号
                        version_match = re.search(r'(\d+)', centos_release)
                        if version_match:
                            version = version_match.group(1)
                            centos_stream_info['version'] = version
                            centos_stream_info['major_version'] = version
                            centos_stream_info['minor_version'] = '0'
            except:
                pass
        
        if not is_centos_stream:
            return centos_stream_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                centos_stream_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                centos_stream_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                centos_stream_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                centos_stream_info['architecture'] = 'ARM32'
            else:
                centos_stream_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                centos_stream_info['is_uefi'] = True
            else:
                centos_stream_info['is_uefi'] = False
        except:
            centos_stream_info['is_uefi'] = False
        
        # 检查版本支持状态
        if centos_stream_info['version'] != 'unknown':
            try:
                version_num = int(centos_stream_info['major_version'])
                
                # 当前支持的版本 (CentOS Stream 9, 10)
                if version_num >= 9:
                    centos_stream_info['supported'] = True
                    centos_stream_info['support_level'] = 'current'
                    centos_stream_info['is_eol'] = False
                
                # EOL版本 (CentOS Stream 8)
                elif version_num == 8:
                    centos_stream_info['supported'] = True  # 仍然支持检测，但标记为EOL
                    centos_stream_info['support_level'] = 'eol'
                    centos_stream_info['is_eol'] = True
                
                # 不支持的版本
                else:
                    centos_stream_info['supported'] = False
                    centos_stream_info['support_level'] = 'none'
                    centos_stream_info['is_eol'] = True
                    
            except ValueError:
                # 无法解析版本号
                centos_stream_info['supported'] = False
                centos_stream_info['support_level'] = 'none'
        
        return centos_stream_info
        
    except Exception as e:
        return centos_stream_info


def detect_fedora_version(system_info=None):
    """
    检测Fedora详细版本信息，包括版本号、架构、EOL状态和CoreOS支持
    
    Args:
        system_info: SystemInfo实例，用于文件读取和命令执行
    
    Returns:
        dict: 包含版本信息的字典
    """
    if system_info is None:
        system_info = SystemInfo()
    
    fedora_info = {
        'is_fedora': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none',  # 'current', 'supported', 'eol', 'none'
        'is_coreos': False,
        'coreos_stream': 'unknown',  # 'stable', 'testing', 'next'
        'build_id': 'unknown',
        'has_podman': False,
        'has_docker': False,
        'has_ostree': False,
        'ostree_version': 'unknown',
        'container_runtime': 'unknown'
    }
    
    try:
        # 检查是否为Fedora系统
        is_fedora = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            os_release_content = system_info.safe_file_read('/etc/os-release')
            if os_release_content and isinstance(os_release_content, str):
                try:
                    os_release = os_release_content.lower()
                    if 'fedora' in os_release:
                        is_fedora = True
                        fedora_info['is_fedora'] = True
                        
                        # 检查是否为CoreOS
                        if 'coreos' in os_release or 'fedora coreos' in os_release:
                            fedora_info['is_coreos'] = True
                        
                        # 提取版本信息
                        for line in os_release_content.split('\n'):
                            if 'VERSION_ID=' in line:
                                version = line.split('=')[1].strip('"\'')
                                fedora_info['version'] = version
                                # 解析主版本号和次版本号
                                if '.' in version:
                                    parts = version.split('.')
                                    fedora_info['major_version'] = parts[0]
                                    fedora_info['minor_version'] = parts[1]
                                else:
                                    fedora_info['major_version'] = version
                                    fedora_info['minor_version'] = '0'
                            elif 'BUILD_ID=' in line:
                                build_id = line.split('=')[1].strip('"\'')
                                fedora_info['build_id'] = build_id
                            elif 'FEDORA_COREOS_STREAM=' in line:
                                stream = line.split('=')[1].strip('"\'')
                                fedora_info['coreos_stream'] = stream.lower()
                except (UnicodeDecodeError, AttributeError):
                    pass
        
        # 方法2: 检查/etc/fedora-release
        if not is_fedora and os.path.exists('/etc/fedora-release'):
            try:
                release_content = system_info.safe_file_read('/etc/fedora-release')
                if release_content and 'fedora' in release_content.lower():
                    is_fedora = True
                    fedora_info['is_fedora'] = True
                    
                    # 从release文件中提取版本号
                    version_match = re.search(r'(\d+)', release_content)
                    if version_match:
                        version = version_match.group(1)
                        fedora_info['version'] = version
                        fedora_info['major_version'] = version
                        fedora_info['minor_version'] = '0'
            except:
                pass
        
        if not is_fedora:
            return fedora_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                fedora_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                fedora_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                fedora_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                fedora_info['architecture'] = 'ARM32'
            else:
                fedora_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                fedora_info['is_uefi'] = True
            else:
                fedora_info['is_uefi'] = False
        except:
            fedora_info['is_uefi'] = False
        
        # 如果检测到CoreOS，获取流信息
        if fedora_info['is_coreos'] and fedora_info['coreos_stream'] == 'unknown':
            fedora_info['coreos_stream'] = detect_coreos_stream(system_info)
        
        # 检查版本支持状态
        if fedora_info['version'] != 'unknown':
            try:
                # CoreOS版本支持逻辑
                if fedora_info['is_coreos']:
                    # CoreOS使用不同的版本号体系
                    if '.' in fedora_info['version']:
                        # 解析CoreOS版本 (如 34.20210529.3.0)
                        major_version = int(fedora_info['version'].split('.')[0])
                        
                        # CoreOS 33+ 基于Fedora 33+，都是支持的
                        if major_version >= 33:
                            fedora_info['supported'] = True
                            fedora_info['support_level'] = 'current'
                            fedora_info['is_eol'] = False
                            fedora_info['coreos_stream'] = 'stable'  # 默认为stable流
                        else:
                            fedora_info['supported'] = False
                            fedora_info['support_level'] = 'none'
                            fedora_info['is_eol'] = True
                    else:
                        # 单一版本号的CoreOS
                        version_num = int(fedora_info['version'])
                        if version_num >= 33:
                            fedora_info['supported'] = True
                            fedora_info['support_level'] = 'current'
                            fedora_info['is_eol'] = False
                            fedora_info['coreos_stream'] = 'stable'
                        else:
                            fedora_info['supported'] = False
                            fedora_info['support_level'] = 'none'
                            fedora_info['is_eol'] = True
                else:
                    # 标准Fedora版本支持逻辑
                    version_num = int(fedora_info['version'])
                    
                    # 当前支持的版本 (Fedora 40, 41)
                    if version_num >= 40:
                        fedora_info['supported'] = True
                        fedora_info['support_level'] = 'current'
                        fedora_info['is_eol'] = False
                    
                    # EOL版本 (Fedora 33-39)
                    elif 33 <= version_num <= 39:
                        fedora_info['supported'] = True  # 仍然支持检测，但标记为EOL
                        fedora_info['support_level'] = 'eol'
                        fedora_info['is_eol'] = True
                    
                    # 不支持的版本
                    else:
                        fedora_info['supported'] = False
                        fedora_info['support_level'] = 'none'
                        fedora_info['is_eol'] = True
                    
            except ValueError:
                # 无法解析版本号，但如果是CoreOS则默认支持
                if fedora_info['is_coreos']:
                    fedora_info['supported'] = True
                    fedora_info['support_level'] = 'current'
                    fedora_info['is_eol'] = False
                    fedora_info['coreos_stream'] = 'stable'
                else:
                    fedora_info['supported'] = False
                    fedora_info['support_level'] = 'none'
        
        # 检测容器化特性（特别是CoreOS）
        if fedora_info['is_coreos']:
            # 检测Podman
            try:
                podman_output = ml('which podman 2>/dev/null')
                if podman_output.strip():
                    fedora_info['has_podman'] = True
                    fedora_info['container_runtime'] = 'podman'
            except:
                pass
            
            # 检测Docker
            try:
                docker_output = ml('which docker 2>/dev/null')
                if docker_output.strip():
                    fedora_info['has_docker'] = True
                    if fedora_info['container_runtime'] == 'unknown':
                        fedora_info['container_runtime'] = 'docker'
            except:
                pass
            
            # 检测OSTree
            try:
                ostree_output = ml('which ostree 2>/dev/null')
                if ostree_output.strip():
                    fedora_info['has_ostree'] = True
                    # 获取OSTree版本
                    try:
                        ostree_version = ml('ostree --version 2>/dev/null').strip()
                        if ostree_version:
                            fedora_info['ostree_version'] = ostree_version
                    except:
                        pass
            except:
                pass
            
            # 检测rpm-ostree
            try:
                rpm_ostree_output = ml('which rpm-ostree 2>/dev/null')
                if rpm_ostree_output.strip():
                    fedora_info['has_ostree'] = True
                    # 获取rpm-ostree状态
                    try:
                        rpm_ostree_status = ml('rpm-ostree status --json 2>/dev/null')
                        if rpm_ostree_status.strip():
                            # 这里可以解析JSON获取更多信息
                            pass
                    except:
                        pass
            except:
                pass
        
        return fedora_info
        
    except Exception as e:
        return fedora_info


def detect_coreos_stream(system_info=None):
    """
    检测Fedora CoreOS的流类型
    
    Args:
        system_info: SystemInfo实例，用于文件读取和命令执行
    
    返回: stable, testing, next 或 unknown
    """
    if system_info is None:
        system_info = SystemInfo()
    try:
        # 检查/etc/os-release中的流信息
        if os.path.exists('/etc/os-release'):
            content = system_info.safe_file_read('/etc/os-release')
            if content:
                for line in content.split('\n'):
                    if 'fedora_coreos_stream=' in line.lower():
                        stream = line.split('=')[1].strip('"\'')
                        return stream.lower()
        
        # 检查更新配置文件
        if os.path.exists('/etc/coreos/update.conf'):
            content = system_info.safe_file_read('/etc/coreos/update.conf')
            if content:
                for line in content.split('\n'):
                    if 'group=' in line.lower():
                        group = line.split('=')[1].strip()
                        # CoreOS组映射到流
                        if 'stable' in group.lower():
                            return 'stable'
                        elif 'testing' in group.lower():
                            return 'testing'
                        elif 'next' in group.lower():
                            return 'next'
        
        # 检查rpm-ostree状态
        try:
            import subprocess
            result = subprocess.run(['rpm-ostree', 'status', '--json'], 
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10)
            if result.returncode == 0:
                import json
                status = json.loads(result.stdout.decode('utf-8'))
                if 'deployments' in status and status['deployments']:
                    deployment = status['deployments'][0]
                    if 'origin' in deployment:
                        origin = deployment['origin']
                        if 'stable' in origin:
                            return 'stable'
                        elif 'testing' in origin:
                            return 'testing'
                        elif 'next' in origin:
                            return 'next'
        except:
            pass
        
        return 'unknown'
    except:
        return 'unknown'


def detect_opensuse_version():
    """
    检测OpenSUSE详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    opensuse_info = {
        'is_opensuse': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'is_uefi': False,
        'codename': 'unknown',
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'current', 'supported', 'eol', 'none'
    }
    
    try:
        # 检查是否为OpenSUSE系统
        is_opensuse = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            with open('/etc/os-release', 'r') as f:
                os_release = f.read().lower()
                if 'opensuse' in os_release or ('suse' in os_release and 'sles' not in os_release):
                    is_opensuse = True
                    opensuse_info['is_opensuse'] = True
                    
                    # 提取版本信息
                    for line in os_release.split('\n'):
                        if 'version_id=' in line:
                            version = line.split('=')[1].strip('"\'')
                            opensuse_info['version'] = version
                            # 解析主版本号和次版本号
                            if '.' in version:
                                parts = version.split('.')
                                opensuse_info['major_version'] = parts[0]
                                opensuse_info['minor_version'] = parts[1]
                            else:
                                opensuse_info['major_version'] = version
                                opensuse_info['minor_version'] = '0'
                        elif 'version_codename=' in line:
                            codename = line.split('=')[1].strip('"\'')
                            opensuse_info['codename'] = codename
        
        # 方法2: 检查/etc/SuSE-release
        if not is_opensuse and os.path.exists('/etc/SuSE-release'):
            try:
                with open('/etc/SuSE-release', 'r') as f:
                    release_content = f.read().strip()
                    if 'opensuse' in release_content.lower():
                        is_opensuse = True
                        opensuse_info['is_opensuse'] = True
                        
                        # 从release文件中提取版本号
                        version_match = re.search(r'(\d+\.\d+)', release_content)
                        if version_match:
                            version = version_match.group(1)
                            opensuse_info['version'] = version
                            parts = version.split('.')
                            opensuse_info['major_version'] = parts[0]
                            opensuse_info['minor_version'] = parts[1]
            except:
                pass
        
        # 方法3: 检查/etc/SUSE-brand
        if not is_opensuse and os.path.exists('/etc/SUSE-brand'):
            try:
                with open('/etc/SUSE-brand', 'r') as f:
                    brand_content = f.read().lower()
                    if 'opensuse' in brand_content:
                        is_opensuse = True
                        opensuse_info['is_opensuse'] = True
            except:
                pass
        
        if not is_opensuse:
            return opensuse_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                opensuse_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                opensuse_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                opensuse_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                opensuse_info['architecture'] = 'ARM32'
            else:
                opensuse_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                opensuse_info['is_uefi'] = True
        except:
            pass
        
        # 检查版本支持状态
        if opensuse_info['version'] != 'unknown':
            try:
                # 处理版本号
                if '.' in opensuse_info['version']:
                    major_ver = float(opensuse_info['major_version'])
                    minor_ver = float(opensuse_info['minor_version'])
                    
                    # 当前支持的版本 (OpenSUSE 15.4, 15.5, 15.6)
                    if major_ver == 15 and minor_ver >= 4:
                        opensuse_info['supported'] = True
                        opensuse_info['support_level'] = 'current'
                        opensuse_info['is_eol'] = False
                    
                    # EOL版本 (OpenSUSE 15.1, 15.2, 15.3)
                    elif major_ver == 15 and 1 <= minor_ver <= 3:
                        opensuse_info['supported'] = True  # 仍然支持检测，但标记为EOL
                        opensuse_info['support_level'] = 'eol'
                        opensuse_info['is_eol'] = True
                    
                    # 旧版本 (OpenSUSE 42.3)
                    elif major_ver == 42 and minor_ver == 3:
                        opensuse_info['supported'] = True  # 仍然支持检测，但标记为EOL
                        opensuse_info['support_level'] = 'eol'
                        opensuse_info['is_eol'] = True
                    
                    # 不支持的版本
                    else:
                        opensuse_info['supported'] = False
                        opensuse_info['support_level'] = 'none'
                        opensuse_info['is_eol'] = True
                else:
                    # 无法解析版本号
                    opensuse_info['supported'] = False
                    opensuse_info['support_level'] = 'none'
                    
            except ValueError:
                # 无法解析版本号
                opensuse_info['supported'] = False
                opensuse_info['support_level'] = 'none'
        
        return opensuse_info
        
    except Exception as e:
        return opensuse_info


def detect_debian_version():
    """
    检测Debian详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    debian_info = {
        'is_debian': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'codename': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'full', 'limited', 'eol', 'none'
    }
    
    try:
        # 检查是否为Debian系统
        is_debian = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            with open('/etc/os-release', 'r') as f:
                os_release = f.read().lower()
                if 'debian' in os_release and 'ubuntu' not in os_release:
                    is_debian = True
                    debian_info['is_debian'] = True
                    
                    # 提取版本信息
                    for line in os_release.split('\n'):
                        if 'version_id=' in line:
                            version = line.split('=')[1].strip('"\'')
                            debian_info['version'] = version
                            # 解析主版本号和次版本号
                            if '.' in version:
                                parts = version.split('.')
                                debian_info['major_version'] = parts[0]
                                debian_info['minor_version'] = parts[1]
                            else:
                                debian_info['major_version'] = version
                                debian_info['minor_version'] = '0'
                        elif 'version_codename=' in line:
                            codename = line.split('=')[1].strip('"\'')
                            debian_info['codename'] = codename
        
        # 方法2: 检查/etc/debian_version
        if not is_debian and os.path.exists('/etc/debian_version'):
            try:
                with open('/etc/debian_version', 'r') as f:
                    debian_version = f.read().strip()
                    # 排除Ubuntu系统
                    if 'ubuntu' not in debian_version.lower():
                        is_debian = True
                        debian_info['is_debian'] = True
                        debian_info['version'] = debian_version
                        
                        # 解析版本号
                        if '.' in debian_version:
                            parts = debian_version.split('.')
                            debian_info['major_version'] = parts[0]
                            debian_info['minor_version'] = parts[1]
                        else:
                            debian_info['major_version'] = debian_version
                            debian_info['minor_version'] = '0'
            except:
                pass
        
        if not is_debian:
            return debian_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                debian_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                debian_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                debian_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                debian_info['architecture'] = 'ARM32'
            else:
                debian_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                debian_info['is_uefi'] = True
            else:
                debian_info['is_uefi'] = False
        except:
            debian_info['is_uefi'] = False
        
        # 定义支持的Debian版本和EOL状态
        debian_versions = {
            # 当前支持版本
            '12': {'codenames': ['bookworm'], 'eol': False, 'support': 'full'},
            '11': {'codenames': ['bullseye'], 'eol': False, 'support': 'full'},
            
            # EOL版本
            '10': {'codenames': ['buster'], 'eol': True, 'support': 'eol'},
            '9': {'codenames': ['stretch'], 'eol': True, 'support': 'eol'},
            '8': {'codenames': ['jessie'], 'eol': True, 'support': 'eol'},
            '7': {'codenames': ['wheezy'], 'eol': True, 'support': 'eol'},
            '6': {'codenames': ['squeeze'], 'eol': True, 'support': 'eol'}
        }
        
        # 检查版本支持状态
        major_ver = debian_info['major_version']
        if major_ver in debian_versions:
            version_info = debian_versions[major_ver]
            debian_info['is_eol'] = version_info['eol']
            debian_info['support_level'] = version_info['support']
            debian_info['supported'] = True
            
            # 设置代号（如果未从os-release获取）
            if debian_info['codename'] == 'unknown' and version_info['codenames']:
                debian_info['codename'] = version_info['codenames'][0]
        
        # 特殊版本检查
        specific_versions = [
            # Debian 12.x系列
            '12.12', '12.11', '12.10', '12.9', '12.8', '12.7', '12.6', '12.5', '12.4', '12.2',
            # Debian 11.x系列
            '11.11', '11.10', '11.9', '11.8', '11.7', '11.6', '11.5', '11.4', '11.3', '11.2', '11.1', '11.0',
            # Debian 10.x系列 (EOL)
            '10.13', '10.12', '10.11', '10.10', '10.9', '10.7', '10.6', '10.5', '10.4', '10.3', '10.2',
            # Debian 9.x系列 (EOL)
            '9.13', '9.12', '9.11', '9.9', '9.8', '9.6',
            # Debian 8.x系列 (EOL)
            '8.11'
        ]
        
        if debian_info['version'] in specific_versions:
            debian_info['supported'] = True
            
            # 根据主版本号设置EOL状态
            if debian_info['version'].startswith(('10.', '9.', '8.')):
                debian_info['is_eol'] = True
                debian_info['support_level'] = 'eol'
            elif debian_info['version'].startswith(('12.', '11.')):
                debian_info['is_eol'] = False
                debian_info['support_level'] = 'full'
        
        return debian_info
        
    except Exception as e:
        return debian_info


def detect_rocky_version():
    """
    检测Rocky Linux详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    system_info = SystemInfo()
    rocky_info = {
        'is_rocky': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'codename': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'current', 'supported', 'eol', 'none'
    }
    
    try:
        # 检查是否为Rocky Linux系统
        is_rocky = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            os_release_content = system_info.safe_file_read('/etc/os-release')
            if os_release_content and isinstance(os_release_content, str):
                try:
                    os_release = os_release_content.lower()
                    if 'rocky' in os_release and 'linux' in os_release:
                        is_rocky = True
                        rocky_info['is_rocky'] = True
                        
                        # 提取版本信息
                        for line in os_release_content.split('\n'):
                            if 'VERSION_ID=' in line:
                                version = line.split('=')[1].strip('"\'')
                                rocky_info['version'] = version
                                # 解析主版本号和次版本号
                                if '.' in version:
                                    parts = version.split('.')
                                    rocky_info['major_version'] = parts[0]
                                    rocky_info['minor_version'] = parts[1]
                                else:
                                    rocky_info['major_version'] = version
                                    rocky_info['minor_version'] = '0'
                            elif 'VERSION_CODENAME=' in line or 'CODENAME=' in line:
                                codename = line.split('=')[1].strip('"\'')
                                rocky_info['codename'] = codename
                except (UnicodeDecodeError, AttributeError):
                    pass
        
        # 方法2: 检查/etc/rocky-release
        if not is_rocky and os.path.exists('/etc/rocky-release'):
            try:
                release_content = system_info.safe_file_read('/etc/rocky-release')
                if release_content and 'rocky' in release_content.lower():
                    is_rocky = True
                    rocky_info['is_rocky'] = True
                    
                    # 从release文件中提取版本号
                    version_match = re.search(r'(\d+\.\d+)', release_content)
                    if version_match:
                        version = version_match.group(1)
                        rocky_info['version'] = version
                        parts = version.split('.')
                        rocky_info['major_version'] = parts[0]
                        rocky_info['minor_version'] = parts[1]
            except:
                pass
        
        if not is_rocky:
            return rocky_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                rocky_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                rocky_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                rocky_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                rocky_info['architecture'] = 'ARM32'
            else:
                rocky_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                rocky_info['is_uefi'] = True
            else:
                rocky_info['is_uefi'] = False
        except:
            rocky_info['is_uefi'] = False
        
        # 定义支持的Rocky Linux版本和EOL状态
        rocky_versions = {
            # 当前支持版本 (Rocky Linux 9.x系列)
            '9': {'eol': False, 'support': 'current'},
            
            # 支持版本 (Rocky Linux 8.x系列)
            '8': {'eol': False, 'support': 'supported'}
        }
        
        # 检查版本支持状态
        major_ver = rocky_info['major_version']
        if major_ver in rocky_versions:
            version_info = rocky_versions[major_ver]
            rocky_info['is_eol'] = version_info['eol']
            rocky_info['support_level'] = version_info['support']
            rocky_info['supported'] = True
        
        # 特定版本检查
        supported_versions = [
            # Rocky Linux 9.x系列
            '9.6', '9.5', '9.4', '9.3', '9.2', '9.1', '9.0',
            # Rocky Linux 8.x系列
            '8.10', '8.9', '8.8', '8.7', '8.6', '8.5'
        ]
        
        if rocky_info['version'] in supported_versions:
            rocky_info['supported'] = True
            
            # 根据主版本号设置支持级别
            if rocky_info['version'].startswith('9.'):
                rocky_info['is_eol'] = False
                rocky_info['support_level'] = 'current'
            elif rocky_info['version'].startswith('8.'):
                rocky_info['is_eol'] = False
                rocky_info['support_level'] = 'supported'
        
        return rocky_info
        
    except Exception as e:
        return rocky_info


def detect_almalinux_version():
    """
    检测AlmaLinux详细版本信息，包括版本号、架构和EOL状态
    
    Returns:
        dict: 包含版本信息的字典
    """
    system_info = SystemInfo()
    almalinux_info = {
        'is_almalinux': False,
        'version': 'unknown',
        'major_version': 'unknown',
        'minor_version': 'unknown',
        'architecture': 'unknown',
        'codename': 'unknown',
        'is_uefi': False,
        'is_eol': False,
        'supported': False,
        'support_level': 'none'  # 'current', 'supported', 'eol', 'none'
    }
    
    try:
        # 检查是否为AlmaLinux系统
        is_almalinux = False
        
        # 方法1: 检查/etc/os-release
        if os.path.exists('/etc/os-release'):
            os_release_content = system_info.safe_file_read('/etc/os-release')
            if os_release_content and isinstance(os_release_content, str):
                try:
                    os_release = os_release_content.lower()
                    if ('almalinux' in os_release or 'alma linux' in os_release or 
                        'id="almalinux"' in os_release or 'id=almalinux' in os_release):
                        is_almalinux = True
                        almalinux_info['is_almalinux'] = True
                        
                        # 提取版本信息
                        for line in os_release_content.split('\n'):
                            if 'VERSION_ID=' in line:
                                version = line.split('=')[1].strip('"\'')
                                almalinux_info['version'] = version
                                # 解析主版本号和次版本号
                                if '.' in version:
                                    parts = version.split('.')
                                    almalinux_info['major_version'] = parts[0]
                                    almalinux_info['minor_version'] = parts[1]
                                else:
                                    almalinux_info['major_version'] = version
                                    almalinux_info['minor_version'] = '0'
                            elif 'VERSION_CODENAME=' in line or 'CODENAME=' in line:
                                codename = line.split('=')[1].strip('"\'')
                                almalinux_info['codename'] = codename
                except (UnicodeDecodeError, AttributeError):
                    pass
        
        # 方法2: 检查/etc/almalinux-release
        if not is_almalinux and os.path.exists('/etc/almalinux-release'):
            try:
                release_content = system_info.safe_file_read('/etc/almalinux-release')
                if release_content and 'almalinux' in release_content.lower():
                    is_almalinux = True
                    almalinux_info['is_almalinux'] = True
                    
                    # 从release文件中提取版本号
                    version_match = re.search(r'(\d+\.\d+)', release_content)
                    if version_match:
                        version = version_match.group(1)
                        almalinux_info['version'] = version
                        parts = version.split('.')
                        almalinux_info['major_version'] = parts[0]
                        almalinux_info['minor_version'] = parts[1]
            except:
                pass
        
        # 方法3: 检查/etc/redhat-release (AlmaLinux也会有这个文件)
        if not is_almalinux and os.path.exists('/etc/redhat-release'):
            try:
                redhat_content = system_info.safe_file_read('/etc/redhat-release')
                if redhat_content and 'almalinux' in redhat_content.lower():
                    is_almalinux = True
                    almalinux_info['is_almalinux'] = True
                    
                    # 从redhat-release文件中提取版本号
                    version_match = re.search(r'(\d+\.\d+)', redhat_content)
                    if version_match:
                        version = version_match.group(1)
                        almalinux_info['version'] = version
                        parts = version.split('.')
                        almalinux_info['major_version'] = parts[0]
                        almalinux_info['minor_version'] = parts[1]
            except:
                pass
        
        # 方法4: 检查/etc/system-release
        if not is_almalinux and os.path.exists('/etc/system-release'):
            try:
                system_content = system_info.safe_file_read('/etc/system-release')
                if system_content and 'almalinux' in system_content.lower():
                    is_almalinux = True
                    almalinux_info['is_almalinux'] = True
                    
                    # 从system-release文件中提取版本号
                    version_match = re.search(r'(\d+\.\d+)', system_content)
                    if version_match:
                        version = version_match.group(1)
                        almalinux_info['version'] = version
                        parts = version.split('.')
                        almalinux_info['major_version'] = parts[0]
                        almalinux_info['minor_version'] = parts[1]
            except:
                pass
        
        # 方法5: 检查hostnamectl命令输出
        if not is_almalinux:
            try:
                hostnamectl_output = ml('hostnamectl').strip()
                if hostnamectl_output and 'almalinux' in hostnamectl_output.lower():
                    is_almalinux = True
                    almalinux_info['is_almalinux'] = True
                    
                    # 从hostnamectl输出中提取版本号
                    version_match = re.search(r'(\d+\.\d+)', hostnamectl_output)
                    if version_match:
                        version = version_match.group(1)
                        almalinux_info['version'] = version
                        parts = version.split('.')
                        almalinux_info['major_version'] = parts[0]
                        almalinux_info['minor_version'] = parts[1]
            except:
                pass
        
        if not is_almalinux:
            return almalinux_info
        
        # 检测系统架构
        try:
            arch_output = get_system_architecture()
            if 'x86_64' in arch_output or 'amd64' in arch_output:
                almalinux_info['architecture'] = '64位'
            elif 'i386' in arch_output or 'i686' in arch_output:
                almalinux_info['architecture'] = '32位'
            elif 'aarch64' in arch_output:
                almalinux_info['architecture'] = 'ARM64'
            elif 'armv7' in arch_output:
                almalinux_info['architecture'] = 'ARM32'
            else:
                almalinux_info['architecture'] = arch_output
        except:
            pass
        
        # 检测UEFI支持
        try:
            if os.path.exists('/sys/firmware/efi'):
                almalinux_info['is_uefi'] = True
            else:
                almalinux_info['is_uefi'] = False
        except:
            almalinux_info['is_uefi'] = False
        
        # 定义支持的AlmaLinux版本和EOL状态
        almalinux_versions = {
            # 当前支持版本 (AlmaLinux 10.x系列)
            '10': {'eol': False, 'support': 'current'},
            
            # 当前支持版本 (AlmaLinux 9.x系列)
            '9': {'eol': False, 'support': 'current'},
            
            # 支持版本 (AlmaLinux 8.x系列)
            '8': {'eol': False, 'support': 'supported'}
        }
        
        # 检查版本支持状态
        major_ver = almalinux_info['major_version']
        if major_ver in almalinux_versions:
            version_info = almalinux_versions[major_ver]
            almalinux_info['is_eol'] = version_info['eol']
            almalinux_info['support_level'] = version_info['support']
            almalinux_info['supported'] = True
        
        # 特定版本检查
        supported_versions = [
            # AlmaLinux 10.x系列
            '10.0',
            # AlmaLinux 9.x系列
            '9.6', '9.5', '9.4', '9.3', '9.2', '9.1', '9.0',
            # AlmaLinux 8.x系列 (包含UEFI版本)
            '8.9', '8.8', '8.7', '8.6', '8.5'
        ]
        
        if almalinux_info['version'] in supported_versions:
            almalinux_info['supported'] = True
            
            # 根据主版本号设置支持级别
            if almalinux_info['version'].startswith('10.'):
                almalinux_info['is_eol'] = False
                almalinux_info['support_level'] = 'current'
            elif almalinux_info['version'].startswith('9.'):
                almalinux_info['is_eol'] = False
                almalinux_info['support_level'] = 'current'
            elif almalinux_info['version'].startswith('8.'):
                almalinux_info['is_eol'] = False
                almalinux_info['support_level'] = 'supported'
        
        return almalinux_info
        
    except Exception as e:
        return almalinux_info


def check_ssh_service_status(distro=None):
    """
    统一的SSH服务状态检测函数
    
    Args:
        distro: Linux发行版类型，如果为None则自动检测
        
    Returns:
        bool: SSH服务是否运行中
    """
    try:
        if distro is None:
            distro = detect_linux_distro()
        
        ssh_service_commands = []
        
        if distro == 'debian_based':
            ssh_service_commands = [
                'systemctl is-active ssh 2>/dev/null',
                'systemctl is-active sshd 2>/dev/null', 
                'service ssh status 2>/dev/null',
                'service sshd status 2>/dev/null'
            ]
        elif distro == 'fedora_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null'
            ]
        elif distro == 'alpine_based':
            ssh_service_commands = [
                'rc-service sshd status 2>/dev/null',
                'rc-service ssh status 2>/dev/null',
                'rc-status | grep sshd 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'alibaba_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'anolis_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'centos_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'chkconfig --list sshd 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'centos_stream_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'rhel_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        elif distro == 'suse_based':
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'systemctl status sshd 2>/dev/null | grep -i active',
                'service sshd status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        else:
            # 通用命令
            ssh_service_commands = [
                'systemctl is-active sshd 2>/dev/null',
                'systemctl is-active ssh 2>/dev/null',
                'service sshd status 2>/dev/null',
                'service ssh status 2>/dev/null',
                'ps aux | grep sshd | grep -v grep 2>/dev/null'
            ]
        
        # 尝试执行命令检查SSH服务状态
        for cmd in ssh_service_commands:
            try:
                output = ml(cmd).strip()
                if output:
                    # 检查输出是否表示服务正在运行
                    if ('active' in output.lower() or 
                        'running' in output.lower() or 
                        'started' in output.lower() or
                        'sshd' in output.lower()):
                        return True
            except:
                continue
        
        return False
        
    except Exception:
        return False


def detect_alibaba_version():
    """检测阿里云Linux版本信息"""
    try:
        version_files = [
            '/etc/alinux-release',
            '/etc/alios-release',
            '/etc/os-release'
        ]
        
        for version_file in version_files:
            if os.path.exists(version_file):
                with open(version_file, 'r') as f:
                    content = f.read().strip()
                    if 'alibaba' in content.lower() or 'alinux' in content.lower():
                        return content
        
        return "Unknown Alibaba Linux Version"
    except Exception:
        return "Unknown Alibaba Linux Version"


def detect_anolis_version():
    """检测Anolis OS版本信息"""
    try:
        version_files = [
            '/etc/anolis-release',
            '/etc/os-release'
        ]
        
        for version_file in version_files:
            if os.path.exists(version_file):
                with open(version_file, 'r') as f:
                    content = f.read().strip()
                    if 'anolis' in content.lower():
                        return content
        
        return "Unknown Anolis OS Version"
    except Exception:
        return "Unknown Anolis OS Version"